package com.whcoding.test.thread;

import com.whcoding.test.dao.mapper.OrmCustomerMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;

// https://mp.weixin.qq.com/s/qL-1YaIMXBwNXqYjtulVcw
public class SaveThreadTransaction {

    private static final Logger log = LoggerFactory.getLogger(SaveThreadTransaction.class);

    @Resource
    SqlContext sqlContext;


    @Autowired
    OrmCustomerMapper ormCustomerMapper;

    /**
     * 测试多线程事务.
     * 在spring中可以使用@Transactional注解去控制事务
     * 在多线程中，这个注解则不会生效
     * @param employeeDOList
     */
//    public void saveThread(List<OrmCustomerVO> employeeDOList) throws SQLException {
//        // 获取数据库连接,获取会话(内部自有事务)
//        SqlSession sqlSession = sqlContext.getSqlSession();
//        Connection connection = sqlSession.getConnection();
//        try {
//            // 设置手动提交
//            connection.setAutoCommit(false);
//            EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
//            //先做删除操作
//            employeeMapper.delete(null);
//            ExecutorService service = ExecutorConfig.getThreadPool();
//            List<Callable<Integer>> callableList = new ArrayList<>();
//            List<List<OrmCustomerVO>> lists = SplitList.averageAssign(employeeDOList, 5);
//            for (int i = 0; i < lists.size(); i++) {
//                List<OrmCustomerVO> list = lists.get(i);
//                Callable<Integer> callable = () -> employeeMapper.saveBatch(list);
//                callableList.add(callable);
//            }
//            //执行子线程
//            List<Future<Integer>> futures = service.invokeAll(callableList);
//            for (Future<Integer> future : futures) {
//                if (future.get() <= 0) {
//                    connection.rollback();
//                    return;
//                }
//            }
//            connection.commit();
//            System.out.println("添加完毕");
//        } catch (Exception e) {
//            connection.rollback();
//            log.info("error出现异常", e);
//        }
//    }
}
